﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using WebApi.Model;
using WebApi.Helpers;
using System.IO;
using System;
using WebApi.Infrastructure;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace WebApi.Controllers
{
    /// <summary>
    /// app调用接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AppController : ControllerBase
    {
        private readonly string savePath = AppSetting.GetValue("WebApiParams:PictureSavePath");
        private readonly ILogger<AppController> logger;
        /*   public IActionResult Index()
           {
               return View();
           }*/
        public AppController(ILogger<AppController> logger)
        {
            this.logger = logger;
        }
        /// <summary>
        /// 通过车牌获取在厂状态的物资列表
        /// </summary>
        /// <param name="role">用户</param>
        /// <returns>message返回信息</returns>  
        [HttpPost("GetGoods")]
        public IActionResult GetGoods(string plate)
        {
            bool result = false;
            string message = "";
            List<RegisterInfo> dbRegisterInfo=null;
            List<Monitor> monitors = new List<Monitor>();
            try
            {
                var db = DbHelper.GetDbConn();
                //获取车辆注册信息
               dbRegisterInfo = db.Queryable<RegisterInfo>().Where(it => it.Plate.Equals(plate) && it.CardStatus.Equals(1)).OrderBy(it => it.Id, SqlSugar.OrderByType.Desc).ToList();
                if (dbRegisterInfo.Count >0)
                {
                    for (int i = 0; i < dbRegisterInfo.Count; i++)
                    {
                        //通过车牌查出是否有继续流程的监磅数据
                        string guid = dbRegisterInfo[i].Guid;
                        var dbMonitor = db.Queryable<Monitor>().Where(it => it.Guid.Equals(guid)).OrderBy(it => it.Id, SqlSugar.OrderByType.Desc).First();
                        if(dbMonitor==null) dbMonitor=new Monitor();
                        dbMonitor.Guid = dbRegisterInfo[i].Guid;
                        dbMonitor.GoodsName = dbRegisterInfo[i].GoodsName;
                        dbMonitor.Company=dbRegisterInfo[i].Company;
              /*          if (dbRegisterInfo[i].CardType != 3)
                            dbMonitor.IsIn = 0;//厂外*/
                        monitors.Add(dbMonitor);
                    }
                   
                    result = true;
                }
                else
                {
                    result = false;
                    message = "未查到该车流程。";
                }
            }
            catch (Exception ex)
            {
                logger.LogError(nameof(GetGoods), ex);
            }
            return Ok(new
            {
                result = result,
                message = message,
                data = monitors
            });
        }
     
        /// <summary>
        /// 保存计量数据
        /// </summary>
        /// <param name="monitor">用户</param>
        /// <returns>message返回信息</returns>  
        [HttpPost("SaveAPPData")]
        public IActionResult SaveAPPData([FromForm] Monitor monitor)
        {
            bool result = false;
            int res = 0;
            string message = "";
            string packName = savePath + DateTime.Now.ToString("yyMMdd") + "\\Pad\\";
            string iname = DateTime.Now.ToString("HHmmssffff");

            if (monitor.Type == "0")
            {//毛重
                monitor.Pic1 = SavePicture(monitor.Pic1, packName, $"{iname}_1.png");
                monitor.Pic2 = SavePicture(monitor.Pic2, packName, $"{iname}_2.png");
                monitor.Pic3 = SavePicture(monitor.Pic3, packName, $"{iname}_3.png");
                monitor.Pic4 = SavePicture(monitor.Pic4, packName, $"{iname}_4.png");
                monitor.Pic5 = null; monitor.Pic6 = null; monitor.Pic7 = null; monitor.Pic8 = null;
                monitor.GrossTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                monitor.Pic5 = SavePicture(monitor.Pic1, packName, $"{iname}_5.png");
                monitor.Pic6 = SavePicture(monitor.Pic2, packName, $"{iname}_6.png");
                monitor.Pic7 = SavePicture(monitor.Pic3, packName, $"{iname}_7.png");
                monitor.Pic8 = SavePicture(monitor.Pic4, packName, $"{iname}_8.png");
                monitor.Pic1 = null; monitor.Pic2 = null; monitor.Pic3 = null; monitor.Pic4 = null;
                monitor.TareTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            try
            {
                var db = DbHelper.GetDbConn();
                //通过车牌查出是否有继续流程的监磅数据
                var dbMonitor = db.Queryable<Monitor>().Where(it => it.Guid.Equals(monitor.Guid) &&it.GoodsName.Equals(monitor.GoodsName)).OrderBy(it => it.Id, SqlSugar.OrderByType.Desc).First();
                if (dbMonitor != null)
                {
                    if (dbMonitor.Flag != 2)
                    {
                        monitor.Flag = dbMonitor.Flag;
                        //0,1存在继续流程的监磅数据，执行update操作
                        if (monitor.Type == "0")
                        {//毛重
                            res = db.Updateable(monitor).UpdateColumns(it =>
                            new
                            {
                                it.GrossWeight,
                                it.GrossTime,
                                it.KouZhong,
                                it.Number,
                                it.KunZhong,
                                it.ShaoBu,
                                it.BeiTai,
                                it.ShuiXiang,
                                it.Drivers,
                                it.YiWu,
                                it.Remark,
                                it.Pic1,
                                it.Pic2,
                                it.Pic3,
                                it.Pic4
                            }).WhereColumns(it => new { it.Guid, it.GoodsName, it.Flag }).ExecuteCommand();//update数据
                            if (res > 0)
                                result = true;
                        }
                        else
                        {//皮重 
                            res = db.Updateable(monitor).UpdateColumns(it =>
                            new
                            {
                                it.TareWeight,
                                it.TareTime,
                                it.KouZhong,
                                it.Number,
                                it.KunZhong,
                                it.ShaoBu,
                                it.BeiTai,
                                it.ShuiXiang,
                                it.Drivers,
                                it.YiWu,
                                it.Remark,
                                it.Pic5,
                                it.Pic6,
                                it.Pic7,
                                it.Pic8
                            }).WhereColumns(it=>new { it.Guid,it.GoodsName,it.Flag}).ExecuteCommand();//update数据
                            if (res > 0)
                                result = true;

                        }
                       
                    }
                    else
                    {
                        //flag=2说明该车没有继续流程的计量，需要判断是否为多种货物物资，
                        //是：获取上一条数据的重量，与当前重量进行比较，判断出皮毛重，并insert一条完整的监磅数据
                        //否：说明是厂内车，insert一条只有一半计量流程的监磅数据
                        if (monitor.GoodsName.Equals("多种货物"))
                        {
                            //是：获取上一条数据的重量，与当前重量进行比较，判断出皮毛重，并insert一条完整的监磅数据
                            if (monitor.Type == "0")
                            {//毛重 
                                monitor.TareWeight = dbMonitor.GrossWeight;
                                monitor.TareTime = dbMonitor.GrossTime;
                                monitor.GrossTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                monitor.Pic5 = dbMonitor.Pic1;
                                monitor.Pic6 = dbMonitor.Pic2;
                                monitor.Pic7 = dbMonitor.Pic3;
                                monitor.Pic8 = dbMonitor.Pic4;
                            }
                            else
                            {//皮重 
                                monitor.GrossWeight = dbMonitor.TareWeight;
                                monitor.GrossTime = dbMonitor.TareTime;
                                monitor.TareTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                monitor.Pic1 = dbMonitor.Pic5;
                                monitor.Pic2 = dbMonitor.Pic6;
                                monitor.Pic3 = dbMonitor.Pic7;
                                monitor.Pic4 = dbMonitor.Pic8;
                            }
                            monitor.Flag = 1;
                            monitor.AddTime = DateTime.Now;
                            res=db.Insertable(monitor).ExecuteCommand();//insert
                            if (res > 0)
                                result = true;
                        }
                        else
                        {
                            //否：说明是厂内车，insert一条只有一半计量流程的监磅数据
                            monitor.Flag = 0;
                          //  monitor.IsIn = 1;
                            monitor.AddTime = DateTime.Now;
                            res=db.Insertable(monitor).ExecuteCommand();//insert
                            if (res > 0)
                                result = true;
                        }
                    }
                }
                else 
                {
                    //未查到该（guid、物资）的数据，说明是新流程车，insert一条一半计量流程的监磅数据
                    monitor.Flag = 0;
                    monitor.AddTime = DateTime.Now;
                    res=db.Insertable(monitor).ExecuteCommand();//insert
                    if (res > 0)
                        result = true;
                }
            }
            catch (Exception ex)
            {
                message=ex.Message;
                logger.LogError(nameof(SaveAPPData), ex);
            }
            /*else
            {
                //查不到流程号,返回失败
                result = false;
                message = "找不到流程号，请检查车牌是否正确或车辆状态";
            }*/

            return Ok(new
            {
                result = result,
                message = message
            });
        }
        ///// <summary>
        ///// 添加app数据
        ///// </summary>
        ///// <param name="monitor">用户</param>
        ///// <returns>message返回信息</returns>  
        //[HttpPost("AddAPPData")]
        //public IActionResult AddAPPData([FromForm] Monitor monitor)
        //{
        //    bool result = false;
        //    string message = "";
        //    try
        //    {
        //        var db = DbHelper.GetDbConn();
        //        //通过车牌查出流程号
        //        //   var dbRegisterInfo = db.Queryable<RegisterInfo>().Where(it => it.Plate.Equals(monitor.Plate) && it.CardStatus.Equals(1)).First();
        //        //   if (dbRegisterInfo != null)
        //        {
        //            //  monitor.Guid = dbRegisterInfo.Guid;
        //            string packName = savePath + DateTime.Now.ToString("yyMMdd") + "\\Pad\\";
        //            string iname = DateTime.Now.ToString("HHmmssffff");
        //            //判断是否新数据
        //            int res = -1;
        //            //     var dbMonitor = db.Queryable<Monitor>().Where(it => it.Guid.Equals(dbRegisterInfo.Guid)).First();
        //            PictureModel pictureModel = new PictureModel();
        //            pictureModel.RegisterInfoGuid = monitor.Guid;
        //            if (monitor.Type == "0")
        //            {//毛重
        //                pictureModel.PadPic1 = SavePicture(monitor.Pic1, packName, $"{iname}_1.png");
        //                pictureModel.PadPic2 = SavePicture(monitor.Pic2, packName, $"{iname}_2.png");
        //                pictureModel.PadPic3 = SavePicture(monitor.Pic3, packName, $"{iname}_3.png");
        //                pictureModel.PadPic4 = SavePicture(monitor.Pic4, packName, $"{iname}_4.png");
        //                monitor.GrossTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //            }
        //            else
        //            {
        //                pictureModel.PadPic5 = SavePicture(monitor.Pic1, packName, $"{iname}_5.png");
        //                pictureModel.PadPic6 = SavePicture(monitor.Pic2, packName, $"{iname}_6.png");
        //                pictureModel.PadPic7 = SavePicture(monitor.Pic3, packName, $"{iname}_7.png");
        //                pictureModel.PadPic8 = SavePicture(monitor.Pic4, packName, $"{iname}_8.png");
        //                monitor.TareTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //            }
        //            res = db.Updateable(monitor).WhereColumns(it => new { it.Guid }).IgnoreColumns(ignoreAllNullColumns: true).IgnoreColumns("AddTime").ExecuteCommand();//保存数据

        //            var updateable = db.Updateable(pictureModel).IgnoreColumns(it => it.Id).IgnoreColumns(it => it.RegisterInfoGuid);
        //            if (string.IsNullOrEmpty(pictureModel.PadPic1)) updateable.IgnoreColumns(it => it.PadPic1);
        //            if (string.IsNullOrEmpty(pictureModel.PadPic2)) updateable.IgnoreColumns(it => it.PadPic2);
        //            if (string.IsNullOrEmpty(pictureModel.PadPic3)) updateable.IgnoreColumns(it => it.PadPic3);
        //            if (string.IsNullOrEmpty(pictureModel.PadPic4)) updateable.IgnoreColumns(it => it.PadPic4);
        //            if (string.IsNullOrEmpty(pictureModel.PadPic5)) updateable.IgnoreColumns(it => it.PadPic5);
        //            if (string.IsNullOrEmpty(pictureModel.PadPic6)) updateable.IgnoreColumns(it => it.PadPic6);
        //            if (string.IsNullOrEmpty(pictureModel.PadPic7)) updateable.IgnoreColumns(it => it.PadPic7);
        //            if (string.IsNullOrEmpty(pictureModel.PadPic8)) updateable.IgnoreColumns(it => it.PadPic8);
        //            logger.LogInformation(JsonConvert.SerializeObject(monitor));
        //            var executeCommand = updateable.Where(it => it.RegisterInfoGuid.Equals(pictureModel.RegisterInfoGuid)).ExecuteCommand();//保存图片，图片路径，执行数据库
        //            if (res == 1)
        //            {
        //                result = true;
        //                message = "";
        //            }
        //            else
        //            {
        //                result = false;
        //                message = "插入数据失败";
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.LogError(nameof(AddAPPData), ex);
        //    }
        //    /*else
        //    {
        //        //查不到流程号,返回失败
        //        result = false;
        //        message = "找不到流程号，请检查车牌是否正确或车辆状态";
        //    }*/

        //    return Ok(new
        //    {
        //        result = result,
        //        message = message
        //    });
        //}
        /// <summary>
        /// 设备维护获取汽车衡重量
        /// </summary>
        /// <param name="role">用户</param>
        /// <returns>message返回信息</returns>  
        [HttpPost("getCheckWeight")]
        public async Task<ReturnModel> getCheckWeight()
        {
            ReturnModel returnModel = new ReturnModel();
            returnModel.Data = await DbHelper.CheckDevice.GetFirstAsync(it => it.Date == DateTime.Now.ToString("yyyy-MM-dd"));
            return returnModel;
        }
        /// <summary>
        /// 设备维护更新维护数据
        /// </summary>
        /// <returns>message返回信息</returns>  
        [HttpPost("updateCheckDevice")]
        public async Task<ReturnModel> updateCheckDevice(CheckDevice check)
        {
            check.Date = DateTime.Now.ToString("yyyy-MM-dd");
            ReturnModel returnModel = new ReturnModel();
            returnModel.Data = await DbHelper.CheckDevice.UpdateAsync(check);
            return returnModel;
        }
      
        private string SavePicture(string base64, string path, string innerName)
        {
            return !string.IsNullOrEmpty(base64) ? FileHelper.SaveImageFromBase64(base64, path, innerName) : string.Empty;
        }

    }
}
